﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Web.Security;

namespace DNA.Mvc.Data.Entity
{
    public class OpenIDRepository : EntityRepository<OpenIdentity>, IOpenIDRepository
    {
        public OpenIDRepository() : base() { }
        public OpenIDRepository(DB dbContext) : base(dbContext) { }

        public bool AddOpenID(string userName, string openid)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("The value could not be null", "userName");
            if (String.IsNullOrEmpty(openid)) throw new ArgumentException("The value could not be null", "openid");

            var _passport = DbSet.FirstOrDefault(p => (p.UserId.Equals(openid, StringComparison.OrdinalIgnoreCase)));

            if (_passport == null)
            {
                DbSet.Add(new OpenIdentity()
                {
                    UserName = userName,
                    UserId = openid
                });
                if (IsOwnContext)
                    Context.SaveChanges();
                return true;
            }
            return false;
        }

        public void DeleteOpenID(string userName, string openid)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("The value could not be null", "userName");

            if (String.IsNullOrEmpty(openid)) throw new ArgumentException("The value could not be null", "openid");

            var _openIdentity = DbSet.FirstOrDefault(p => (p.UserName.Equals(userName) && p.UserId.Equals(openid, StringComparison.OrdinalIgnoreCase)));
            if (_openIdentity != null)
            {
                this.Delete(_openIdentity);
                if (IsOwnContext)
                    Context.SaveChanges();
            }
        }

        public IEnumerable<OpenIdentity> GetUserIDs(string userName)
        {
            if (String.IsNullOrEmpty(userName)) throw new ArgumentException("The value could not be null", "userName");
            return Filter(p => p.UserName == userName);
        }

        public MembershipUser Find(string openId)
        {
            var _openIdentity = DbSet.FirstOrDefault(p => p.UserId.Equals(openId, StringComparison.OrdinalIgnoreCase));
            if (_openIdentity != null)
                return Membership.GetUser(_openIdentity.UserName);
            else
                return null;
        }
    }
}
